package com.yuanfeng.userms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.oos.OssUploadUpdateParamDTO;
import com.yuanfeng.commoms.dto.shop.GateStoreUpdateDTO;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.dto.userms.UserPointLogDTO;
import com.yuanfeng.commoms.dto.userms.UserTokenBeanDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.util.secverifyapiutil.QRCodeUtil;
import com.yuanfeng.commoms.vo.fx.VKUserInfoVO;
import com.yuanfeng.commoms.vo.job.AcquiescenceVO;
import com.yuanfeng.commoms.vo.user.*;
import com.yuanfeng.userms.context.LoginContext;
import com.yuanfeng.userms.dto.MemberMessageListDTO;
import com.yuanfeng.userms.entity.*;
import com.yuanfeng.userms.feign.BaseServiceClient;
import com.yuanfeng.userms.feign.BusinessServiceClient;
import com.yuanfeng.userms.feign.PaymentServiceClient;
import com.yuanfeng.userms.feign.ThirdPartyServiceClient;
import com.yuanfeng.userms.mapper.*;
import com.yuanfeng.userms.service.*;
import com.yuanfeng.userms.vo.*;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
*
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfoEntity>
implements UserInfoService{

    @Autowired
    private BaseServiceClient baseServiceClient;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private PaymentServiceClient paymentServiceClient;

    @Autowired
    private UserInfoDetailService userInfoDetailService;

    @Autowired
    private UserBindConnectService userBindConnectService;

    @Autowired
    private UserPointsLogService userPointsLogService;
    @Autowired
    private UserSellerBaseService userSellerBaseService;
    @Resource
    private UserBusinessInfoMapper userBusinessInfoMapper;
    @Resource
    private UserSellerGroupMapper userSellerGroupMapper;
    @Resource
    private UserPlatformMessageMapper userPlatformMessageMapper;
    @Autowired
    private BusinessServiceClient businessServiceClient;
    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;
    @Resource
    private UserInfoDetailMapper userInfoDetailMapper;
    @Autowired
    private UserLiveStatisticsService userLiveStatisticsService;
    @Resource
    private UserBusinessEmployeeMapper userBusinessEmployeeMapper;
    @Resource
    private UserPlusInfoMapper userPlusInfoMapper;

    private static final Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    @Override
    public UserInfoVO getUserInfoByMobile(String userMobile) {
        return this.baseMapper.getUserInfoByPhoneNumber(userMobile);
    }

    @Override
    public UserInfoVO getUserInfoByPhoneNumber1(String userMobile, String shopId) {
        return this.baseMapper.getUserInfoByPhoneNumber1(userMobile,shopId);
    }

    @Override
    public ResponseResult querUserInfoByParams(UserInfoVO vo) {
        UserInfoVO userInfoVO=this.baseMapper.querUserInfoByParams(vo);
        return ResponseResult.success(userInfoVO);
    }

    @Override
    public ResponseResult queryUserInfo(UserInfoVO userInfoVO) {
        UserInfoEntity userInfoEntity=this.baseMapper.selectOne(new LambdaQueryWrapper<UserInfoEntity>()
                                          .eq(userInfoVO.getUserId()!=null,UserInfoEntity::getUserId,userInfoVO.getUserId())
                                          .eq(userInfoVO.getUserMobile()!=null,UserInfoEntity::getUserMobile,userInfoVO.getUserMobile())
                                          .eq(userInfoVO.getShopId()!=null,UserInfoEntity::getShopId,userInfoVO.getShopId())
                                          .isNull(userInfoVO.getShopId()==null,UserInfoEntity::getShopId)
                                          .eq(userInfoVO.getIsDelete()!=null,UserInfoEntity::getIsDelete,userInfoVO.getIsDelete())
                                          .between(userInfoVO.getUserState()!=null,UserInfoEntity::getUserState,CommonType.userState.NOT_ACTIVE.getCode(),CommonType.userState.CERTIFIED.getCode()));
        return ResponseResult.success(userInfoEntity);
    }

    @Override
    public ResponseResult queryUserInfoByUserInfoVO(Map<String, String> map) {
        QueryWrapper<UserInfoEntity> queryWrapper = new QueryWrapper<>();
        if (null != map && null != map.get("userId")) {
            queryWrapper.eq("user_id", map.get("userId"));
        }
        if (null != map && null != map.get("userMobile")) {
            queryWrapper.eq("user_mobile", map.get("userMobile"));
        }
        UserInfoEntity userInfoEntity = this.baseMapper.selectOne(queryWrapper);
        if (null != userInfoEntity) {
            userInfoEntity.setUserNickname(userInfoEntity.getUserNickname() == null
                    ? userInfoEntity.getUserName() : userInfoEntity.getUserNickname());
        }
        return ResponseResult.success(userInfoEntity);
    }

    @Override
    public ResponseResult queryUserInfoByUserId(String userId) {
        UserInfoVO userInfo = this.baseMapper.getUserInfoByUserId2(userId);
        return ResponseResult.success(userInfo);
    }

    @Override
    public ResponseResult updateUserInfoByMap(Map<String, String> map) {
        QueryWrapper<UserInfoEntity> queryWrapper = new QueryWrapper<>();

        if (null != map && null != map.get("userId")) {
            queryWrapper.eq("user_id", map.get("userId"));
        }
        if (null != map && null != map.get("userMobile")) {
            queryWrapper.eq("user_mobile", map.get("userMobile"));
        }
        UserInfoEntity businessInfoEntity = this.baseMapper.selectOne(queryWrapper);
        if (null != map && null != map.get("password")) {
            businessInfoEntity.setPassword(map.get("password"));
        }
        Date now = new Date();
        businessInfoEntity.setUserLastloginTime(now);
        businessInfoEntity.setUserCountLogin(businessInfoEntity.getUserCountLogin() + 1);

        int flag = this.baseMapper.updateById(businessInfoEntity);

        return flag == CommonType.commonStatus.YES.getCode() ? ResponseResult.success() : ResponseResult.fail();
    }

    @Override
    public ResponseResult updateMemberIntegral(MemberMessageListIntegralDTO param) {
        try {
            if(param.getIntegral() < 0){
                //积分不能小于0
                return ResponseResult.fail(BizCodeEnume.INTEGRAL_CANNOT_BE_LESS_THAN_0.getCode(),BizCodeEnume.INTEGRAL_CANNOT_BE_LESS_THAN_0.getMsg());
            }
            if(param.getUserIdList().size() < 0){
                //用户id为空
                return ResponseResult.fail(BizCodeEnume.USER_ID_IS_NULL.getCode(),BizCodeEnume.USER_ID_IS_NULL.getMsg());

            }
            //获取所有用户id
            List<String> userIdList = param.getUserIdList();
            Integer userIntegral = null;
            for (String userId : userIdList) {

                QueryWrapper<UserInfoEntity> queryWrapper = new QueryWrapper<>();
                //获取当前用户的积分
                queryWrapper.eq("user_id", userId);

                UserInfoEntity userInfoEntity = this.baseMapper.selectOne(queryWrapper);

                userIntegral = userInfoEntity.getUserIntegral();
                //type 1是增加积分 0 是扣除积分
                //便利 添加积分
                if (param.getType().equals(CommonType.commonStatus.YES.getCode())) {
                    Integer temp = userIntegral + param.getIntegral();

                    userInfoEntity.setUserIntegral(temp);

                } else {
                    //如果当前用户的积分 小于 等于 平台扣除的积分直接赋值为 0
                    Integer temp = userIntegral - param.getIntegral();

                    if (temp <= 0) {
                        userInfoEntity.setUserIntegral(0);

                    } else {
                        userInfoEntity.setUserIntegral(temp);
                    }

                }
                this.baseMapper.update(userInfoEntity, queryWrapper);

                //积分修改完成 修改会员等级
                Map<String, Object> map = new HashMap<>();
                map.put("gradeStart", CommonType.commonStatus.YES.getCode());
                map.put("userIntegral", userIntegral);
                map.put("userId", userId);
                baseServiceClient.updateTagClassByUserId(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL.getCode(),BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
    }

    @Override
    public Integer updateIsNew(Map<String, String> paraMap) {
        Integer torf = null;
        try {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
            torf = this.baseMapper.updateUserIsNew(userInfo.getUserId());
            UserInfoVO newUserInfo = this.baseMapper.getUserInfoByPhoneNumber(userInfo.getUserMobile());
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + paraMap.get("token"), objectMapper.writeValueAsString(newUserInfo),
                    YFConfig.TOKEN_OUTTIME);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return torf;
    }

    @Override
    public ResponseResult register(Map<String, String> map) throws UnknownHostException, TransactionException {
        String userMobile = map.get("userMobile");
        String phoneCode = map.get("phoneCode");
        //判断shopId是否为空
        String shopId = map.get("shopId");
        String sessionPhoneCode = RedisUtil.get(userMobile);
        if (StringUtils.isNotEmpty(sessionPhoneCode)) {
            //判断验证码是否正确
            if (!phoneCode.equals(sessionPhoneCode)) {
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE.getCode(), BizCodeEnume.INCORRECT_VERIFICATION_CODE.getMsg());
            }
        } else {
            //判断验证码是否失效
            return ResponseResult.fail(BizCodeEnume.VERIFICATION_CODE_OVERDUE.getCode(), BizCodeEnume.VERIFICATION_CODE_OVERDUE.getMsg());
        }
            //走pc注册
            int checkuserId = this.baseMapper.selectCount(new LambdaQueryWrapper<UserInfoEntity>()
                                 .eq(UserInfoEntity::getUserMobile,userMobile)
                                 .between(UserInfoEntity::getUserState,CommonType.userState.NOT_ACTIVE.getCode(),CommonType.userState.CERTIFIED.getCode())
                                 .isNull(UserInfoEntity::getShopId));
            if (checkuserId>0) {
                //手机号存在
                return ResponseResult.fail(BizCodeEnume.PHONE_EXSIT_EXCEPTION.getCode(), BizCodeEnume.PHONE_EXSIT_EXCEPTION.getMsg());
            }

            //短信校验后就删除
            RedisUtil.remove(userMobile);
            //判断密码是否为空
            if (null == map.get("password") || "".equals(map.get("password"))) {
                return ResponseResult.fail(BizCodeEnume.PASSWORD_NOT_STANDARD.getCode(), BizCodeEnume.PASSWORD_NOT_STANDARD.getMsg());
            }


            //将密码加密
            String password = PasswordUtils.BCryptPasswordEncoder(map.get("password"));

            String actionIp = IpUtils.getIpAddress();
            logger.debug("用户ip" + actionIp);
            /* String actionIp = "60.521.521.21"; */

            //用户信息
            UserInfoEntity record = new UserInfoEntity();
            record.setUserMobile(userMobile);
            record.setPassword(password);
            record.setUserLastloginTime(new Date());
            record.setUserLastloginIp(IpUtils.getIpAddress());


            //用户详情
            UserInfoDetaileEntity insertUserInfoDetail = new UserInfoDetaileEntity();
            insertUserInfoDetail.setUserRegTime(System.currentTimeMillis() / 1000);
            insertUserInfoDetail.setUserRegIp(IpUtils.getIpAddress());
            insertUserInfoDetail.setUserPlatform(Integer.parseInt(map.get("platForm")));


            UserBindConnectEntity userBindMap = new UserBindConnectEntity();
            String bindId = null;
            if (shopId == null || shopId == ""){
                bindId = "mobile_" + userMobile;
            }else{
                bindId = "mobile_" + userMobile + "_" + shopId;
            }
            userBindMap.setBindId(bindId);
            userBindMap.setBindType(Byte.parseByte(CommonType.bindType.MOBILE.getCode().toString()));


            // 向积分表插入积分
            UserPointsLogEntity userPointLog = new UserPointsLogEntity();
            userPointLog.setPointsLogType(CommonType.pointsLogType.GAIN.getCode());
            userPointLog.setClassId(CommonType.pointType.REGISTRATION.getCode());
            userPointLog.setPointsLogTime(new Date());
            userPointLog.setPointsLogDesc(BizCodeEnume.MEMBER_REGISTRATION.getMsg());
            userPointLog.setPointsLogFlag("reg");


            if (Boolean.FALSE.equals(insertUserInfo(record, insertUserInfoDetail, userBindMap, userPointLog))) {

                return ResponseResult.fail(BizCodeEnume.REGISTRATION_FAIL.getMsg());
            }

            String userId =  RedisUtil.get(YFConfig.YF_USER_LOGON_USERID + userMobile);

            try {
                ResponseResult torf = paymentServiceClient.createUser(userId);
                logger.info("userId在pay库中注册：" + torf.getCode());
            } catch (Exception e) {
                logger.info(e.getMessage());
            }

            logger.info("用户：" + userId + "注册");

            return ResponseResult.success(BizCodeEnume.REGISTRATION_SUCCESS.getMsg(),userId);

    }

    /**
     * 1.1 二维码注册时加userParentId 插入用户信息，加入三个语句有一个不成功，则回滚 并且向积分表中插入一条积分记录（注册有五十积分）
     *
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Boolean insertUserInfo(UserInfoEntity userinfo, UserInfoDetaileEntity insertUserInfoDetail,
                                  UserBindConnectEntity userBindMap, UserPointsLogEntity userPointLog) throws TransactionException {
        try {
            //查询积分规则
            ResponseResult resultResp = baseServiceClient.queryIntegralRules();
            Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();

            //雪花算法生成用户id
            String userId = SnowflakeIdWorker.getSnowId();

            userinfo.setUserId(userId);
            userinfo.setUserName(userinfo.getUserMobile());
            userinfo.setUserCountLogin(1);
            userinfo.setUserIsNew(CommonType.commonStatus.YES.getCode());
            userinfo.setUserIntegral(integralRules.get("ruleRegister"));
            userinfo.setCreateTime(new Date());
            //保存用户
            int one = this.baseMapper.insert(userinfo);

            ResponseResult avatorMap = baseServiceClient.selectByConfigKey("photo_user_logo");
            Map<String, Object> configMap = (Map<String, Object>) avatorMap.getData();
            String userAvator = configMap.get("configValue").toString();
            insertUserInfoDetail.setUserId(userId);
            insertUserInfoDetail.setCreateUser(userinfo.getUserMobile());
            insertUserInfoDetail.setUserAvatar(userAvator);
            insertUserInfoDetail.setUserMobileVerify(1);
            //保存用户详情
            Boolean two= userInfoDetailService.save(insertUserInfoDetail);


            userBindMap.setUserId(userId);
            userBindMap.setCreateUser(userinfo.getUserMobile());
            //保存用户绑定表
            Boolean three  = userBindConnectService.save(userBindMap);


            //添加积分变更表
            userPointLog.setPointsLogPoints(integralRules.get("ruleRegister"));
            userPointLog.setPointsLogOperate("会员注册");
            userPointLog.setUserId(userId);
            Boolean four = userPointsLogService.save(userPointLog);

            //修改会员等级
            Map<String, Object> gradeMap = new HashMap<>();
            gradeMap.put("ruleRegister", integralRules.get("ruleRegister"));
            gradeMap.put("userId", userId);
            ResponseResult result = baseServiceClient.saveTagClass(gradeMap);

            UserInfoVO ui = new UserInfoVO();
            ui.setUserId(userId);
            LoginContext context = new LoginContext(ui);
            LoginContext.binding(context);

            //判断是否添加成功
            if (CommonType.commonStatus.YES.getCode() == one
                    && two
                    && three
                    && four
                    && CommonStatusEnum.SUCCESS.getCode() == result.getCode()) {
                RedisUtil.set(YFConfig.YF_USER_LOGON_USERID + userinfo.getUserMobile(), userId);
                return true;
            } else {
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                return false;
            }
        } catch (Exception e) {
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            throw new RuntimeException(e.getMessage());

        }

    }

    @Override
    public Integer queryMemberMessageListIntegral(String userId) {
        //查询用户积分
        return this.baseMapper.queryMemberMessageListIntegral(userId);
    }

    @Override
    public ResponseResult queryPersonalDiscount(UserTokenBeanDTO userTokenBeanDTO) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(userTokenBeanDTO.getToken());
        Map<String, Object> stringObjectMap = this.baseMapper.queryPersonalDiscount(userInfo.getUserId());
        Integer integral = this.baseMapper.queryMemberMessageListIntegral(userInfo.getUserId());
        stringObjectMap.put("userIntegral",integral);

        return ResponseResult.success(stringObjectMap);
    }

    @Override
    public ResponseResult getUserMemberInformation(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        MemberInformationVO memberInformation = new MemberInformationVO();
        memberInformation.setUserName(userInfo.getUserName());
        memberInformation.setUserAvatar(userInfo.getUserAvatar());

        //获取当前积分
        Integer presentIntegra=  this.baseMapper.queryMemberMessageListIntegral(userInfo.getUserId());
        memberInformation.setMemberIntegral(presentIntegra);


        //获取会员等级名称
        Map<String, Object> memberClassIdByUserId = baseServiceClient.queryMemberShipGradeByUserId(userInfo.getUserId());
        if(null != memberClassIdByUserId) {
            memberInformation.setMemberName(memberClassIdByUserId.get("grade_name")+"");
            memberInformation.setMemberUrl(memberClassIdByUserId.get("grade_url")+"");
            memberInformation.setGradeDiscount(String.format("%.1f",(Double)memberClassIdByUserId.get("grade_discount") * 10));
        }

        memberInformation.setIsplusMember(userInfo.getPlusMember());
        memberInformation.setThaliType(userInfo.getThaliType());
        Integer maxMemberIntegral = baseServiceClient.getMaxMemberIntegral();
        if(maxMemberIntegral == null || presentIntegra >= maxMemberIntegral){

            memberInformation.setCode(2);
            return ResponseResult.success("您已经是最高等级的会员", memberInformation);
        }

        //获取下一级积分
        ResponseResult memberIntegralDistance = baseServiceClient.getMemberIntegralDistance(userInfo.getUserId());
        Map<String,Object> memberMap = (HashMap) memberIntegralDistance.getData();


        //下一级积分
        Integer grade_rule =(Integer) memberMap.get("grade_rule") ;
        Integer f = grade_rule - presentIntegra;
        memberInformation.setDistanceIntegral(f);
        memberInformation.setMemberNameNext((String) memberMap.get("grade_name"));
        memberInformation.setCode(1);
        memberInformation.setNextGradeRule(grade_rule);

        return ResponseResult.success(memberInformation);
    }

    @Override
    public String checkPhoneNumber(Map<String, String> paraMap) {
        String userId = this.baseMapper.checkPhoneNumber(paraMap);
        return userId;
    }

    @Override
    public ResponseResult businessegInsert(Map<String, String> map) throws UnknownHostException, TransactionException {
        String userMobile = map.get("userMobile");
        String phoneCode = map.get("phoneCode");
        String sessionPhoneCode = RedisUtil.get(userMobile);
        String checkuserId = this.baseMapper.checkPhoneNumber(map);
        if (StringUtils.isNotEmpty(sessionPhoneCode)) {
            //判断验证码是否正确
            if (!phoneCode.equals(sessionPhoneCode)) {
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE.getCode(), BizCodeEnume.INCORRECT_VERIFICATION_CODE.getMsg());
            }
        } else {
            //判断验证码是否失效
            return ResponseResult.fail(BizCodeEnume.VERIFICATION_CODE_OVERDUE.getCode(), BizCodeEnume.VERIFICATION_CODE_OVERDUE.getMsg());
        }
        if (null != checkuserId && !"".equals(checkuserId)) {
            //手机号存在
            return ResponseResult.fail(BizCodeEnume.PHONE_EXSIT_EXCEPTION.getCode(), BizCodeEnume.PHONE_EXSIT_EXCEPTION.getMsg());
        }
        //短信校验后就删除
        RedisUtil.remove(userMobile);
        //判断密码是否为空
        if (null == map.get("password") || "".equals(map.get("password"))) {
            return ResponseResult.fail(BizCodeEnume.PASSWORD_NOT_STANDARD.getCode(), BizCodeEnume.PASSWORD_NOT_STANDARD.getMsg());
        }
//        //校验密码规则
//        ResponseResult resultMap= checkPassword(map.get("password"));
//        if (resultMap.getCode()==CommonStatusEnum.FAIL.getCode()) {
//            return resultMap;
//        }
        //将密码加密
        String password = PasswordUtils.BCryptPasswordEncoder(map.get("password"));

        String actionIp = IpUtils.getIpAddress();
        logger.debug("用户ip" + actionIp);

        //用户信息
        UserInfoEntity record = new UserInfoEntity();
        record.setUserMobile(userMobile);
        record.setPassword(password);
        record.setUserLastloginTime(new Date());
        record.setUserLastloginIp(actionIp);

        //用户详情
        UserInfoDetaileEntity insertUserInfoDetail = new UserInfoDetaileEntity();
        insertUserInfoDetail.setUserRegTime(System.currentTimeMillis() / 1000);
        insertUserInfoDetail.setUserRegIp(actionIp);
        insertUserInfoDetail.setUserPlatform(Integer.parseInt(map.get("platForm")));

        UserBindConnectEntity userBindMap = new UserBindConnectEntity();
        String bindId = "mobile_" + userMobile;
        userBindMap.setBindId(bindId);
        userBindMap.setBindType(Byte.parseByte(CommonType.bindType.MOBILE.getCode().toString()));

        // 向积分表插入积分
        UserPointsLogEntity userPointLog = new UserPointsLogEntity();
        userPointLog.setPointsLogType(CommonType.pointsLogType.GAIN.getCode());
        userPointLog.setClassId(CommonType.pointType.REGISTRATION.getCode());
        userPointLog.setPointsLogTime(new Date());
        userPointLog.setPointsLogDesc(BizCodeEnume.MEMBER_REGISTRATION.getMsg());
        userPointLog.setPointsLogFlag("reg");

        if (Boolean.FALSE.equals(insertUserInfo(record, insertUserInfoDetail, userBindMap, userPointLog))) {
            return ResponseResult.fail(BizCodeEnume.REGISTRATION_FAIL.getMsg());
        }


        String userId =  RedisUtil.get(YFConfig.YF_USER_LOGON_USERID + userMobile);
        try {
            ResponseResult torf = paymentServiceClient.createUser(userId);
            logger.info("userId在pay库中注册：" + torf);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }

        logger.info("用户：" + userId + "注册");
        //更新为企业用户
        Map<String, Object> businessegMap = new HashMap<>();
        businessegMap.put("userId", userId);
        this.baseMapper.businessUpdate(businessegMap);

        //相关信息插入企业用户表
        businessegMap.put("companyName", map.get("companyName"));
        businessegMap.put("taxId", map.get("taxId"));
        businessegMap.put("businessLicense", map.get("businessLicense"));
        userBusinessInfoMapper.insertBusinessUser(businessegMap);

        logger.info("用户：" + userId + "注册");

        return ResponseResult.success(BizCodeEnume.REGISTRATION_SUCCESS.getMsg(),userId);
    }

    @Override
    public ResponseResult updateUcenterInfo(Map<String, Object> paraMap) {
        try {
            String tokenString = paraMap.get("token").toString();
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(tokenString);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String userBirth = null;
            if(null != paraMap.get("userBirth") && !"".equals(paraMap.get("userBirth"))){
                String[] dateStrs = paraMap.get("userBirth").toString().split("-");
                for(int i=0;i<dateStrs.length;i++){
                    if(dateStrs[i].length() == 1){
                        dateStrs[i] = "0".concat(dateStrs[i]);
                    }
                }
                String fomDate = dateStrs[0]+"-"+dateStrs[1]+"-"+dateStrs[2];
                Date date = simpleDateFormat.parse(fomDate);
                userBirth = simpleDateFormat.format(date);
            }
            paraMap.put("userId", userInfo.getUserId());
            paraMap.put("userBirth", userBirth);

            Integer torf = userInfoDetailMapper.updateUcenterInfo(paraMap);
            if (1 == torf) {
                UserInfoVO ui = this.baseMapper.getUserInfoByUserId(userInfo.getUserId());
                RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + tokenString, objectMapper.writeValueAsString(ui),
                        YFConfig.TOKEN_OUTTIME);
                return ResponseResult.success("修改成功");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult checkPayTransferInfo(Map<Object, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExistToken) {
                UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
                String userId = userInfo.getUserId();
                String payeeAccount = (String) map.get("payeeAccount");// 收款人账号
                String rpcUserId = this.baseMapper.queryPayeeAccountUserId(payeeAccount);
                if (rpcUserId == null) {
                    return ResponseResult.fail(0, "账号不存在，请输入正确账号或确认账号是否正确！");
                } else if (userId.equals(rpcUserId)) {
                    return ResponseResult.fail(0, "请勿给本账号转账！");
                } else {
                    return ResponseResult.success(rpcUserId);
                }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
    }
    @Override
    public ResponseResult userLogOut(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        RedisUtil.remove(YFConfig.YF_USER_TOKEN_USER + token);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult getUser(Map<String, String> paraMap) throws IllegalAccessException {
        String token = paraMap.get("token");
        String json = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        if (null == json || json.isEmpty()) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
        String bindOpenid = userInfo.getBindOpenid();
        if (!StringUtils.isEmpty(bindOpenid)) {
            //根据openid获取用户昵称
            Map<String, Object> outMap = userBindConnectService.getMap(new LambdaQueryWrapper<UserBindConnectEntity>()
                                        .eq(UserBindConnectEntity::getBindOpenid,bindOpenid));
            userInfo.setUserNickname(outMap.get("bind_nickname").toString());
            if (!org.springframework.util.StringUtils.isEmpty(outMap.get("bind_avator"))) {
                userInfo.setUserAvatar(outMap.get("bind_avator").toString());
            }
        }
        String platForm = paraMap.get("platForm");
        if (null != platForm && !platForm.isEmpty()) {
            if (platForm.equals("5")) {

               // userInfo.setInviteSubsiteId(wapLoginService.queryUserConstant()); // 0是不展示1是展示
            }
        }
        Integer shopType=CommonType.storeType.SELLER_STORE.getCode();
        if(userInfo.getShopId()!=null){
            Map<String, Object>  map=this.baseMapper.selectByShopInfo(userInfo.getShopId());
            if(map!=null){
                shopType=Integer.valueOf(map.get("shopType").toString());
                userInfo.setShopType(shopType);
            }

        }
        Map<String, String> shopMap = new HashMap<>();
        shopMap.put("userId", userInfo.getUserId() + "");
        //开店成功
        shopMap.put("shopStatus", CommonType.storeStatus.SUCCESSFULLY.getCode() + "");
        //买家店铺
        shopMap.put("shopType",shopType+ "");
        //查询是否正常商家
        ResponseResult shopResult = businessServiceClient.queryShopStatus(shopMap);
        if (null != shopResult.getData()) {
            userInfo.setIsBusiness(1);
        } else {
            userInfo.setIsBusiness(2);
        }
        // 判断用户是否微客
        VKUserInfoVO vkUserInfo = this.baseMapper.queryUserInfoIndenty(userInfo.getUserId());
        if (null != vkUserInfo && vkUserInfo.getVkState().intValue() == 1) {
            userInfo.setVkState(1);
        } else {
            userInfo.setVkState(2);
        }
        //品牌店铺先隐藏 账号设置和门店  chainAccount 门店  permissionGroup账号
        if (userInfo.getShopType() != null && userInfo.getSellerIsAdmin() != null && userInfo.getSellerIsAdmin() == 1) {
            if (userInfo.getShopType() == 3 ) {
                String s = userSellerGroupMapper.selectById(2).getLimits();
                userInfo.setLimits(s);
            }
        }

        UserPlusInfoEntity entity = userPlusInfoMapper.selectOne(new LambdaUpdateWrapper<UserPlusInfoEntity>()
                .eq(UserPlusInfoEntity::getUserId, userInfo.getUserId()));
        if (entity== null){
            //未开通
            userInfo.setPlusMember(2);
        }else if (entity.getThaliStatus() == 1){
            //开通
            userInfo.setPlusMember(1);
            userInfo.setThaliType(entity.getThaliStatus());
        }else if (entity.getThaliStatus() == 0){
            //过期
            userInfo.setPlusMember(0);
        }

        // UserInfo 转 map 方便扩展字段 不能在UserInfo中新增字段否则会影响其他服务token 解析
        //将对象转换为map
        Map data = ParseMapUtils.beanToMap(userInfo);
        //未读消息数量
        data.put("unreadMessageNum",userPlatformMessageMapper.selectCount(new LambdaQueryWrapper<UserPlatformMessageEntity>()
                                    .eq(UserPlatformMessageEntity::getIsReader,CommonType.commonStatus.NO.getCode())
                                    .eq(UserPlatformMessageEntity::getUserId,userInfo.getUserId())));

        return ResponseResult.success(data);
    }

    @Override
    public ResponseResult uploadImg(Map<String, String> paraMap) {
        try {
            String tokenString = paraMap.get("token");
            String userInfoString = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + tokenString);
            UserInfoDTO userInfo = objectMapper.readValue(userInfoString, UserInfoDTO.class);
            OssUploadUpdateParamDTO oss = new OssUploadUpdateParamDTO();
            if (paraMap.get("base64Str") == null) {
                return ResponseResult.fail(BizCodeEnume.PLEASE_SELECT_AN_IMAGE);
            }
            oss.setBase64Str(paraMap.get("base64Str"));
            oss.setStreamName(".png");
            ResponseResult resultResp = thirdPartyServiceClient.uploadPic(oss);
            String photoUrl = (String) resultResp.getData();

            Boolean torf = uploadPhoto(userInfo.getUser().getUserId(), photoUrl);
            if (torf) {
                String mobilePhone = userInfo.getUser().getUserMobile();
                UserInfoVO userInfoVO=new UserInfoVO();
                userInfoVO.setUserMobile(mobilePhone);
                userInfoVO.setLoginType(CommonType.commonStatus.NO.getCode());
                UserInfoVO newUserInfo = this.baseMapper.querUserInfoByParams(userInfoVO);
                Map<String, String> shopMap = new HashMap<>();
                shopMap.put("userId", userInfo.getUser().getUserId() + "");
                //开店成功
                shopMap.put("shopStatus", CommonType.storeStatus.SUCCESSFULLY.getCode() + "");
                //买家店铺
                shopMap.put("shopType", CommonType.storeType.SELLER_STORE.getCode() + "");

                //查询是否正常商家
                ResponseResult shopResult = businessServiceClient.queryShopStatus(shopMap);
                if (null != shopResult.getData()) {
                    newUserInfo.setIsShop(CommonType.commonStatus.YES.getCode());
                } else {
                    newUserInfo.setIsShop(CommonType.commonStatus.NO.getCode());
                }
                userInfo.setUser(newUserInfo);
                RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + tokenString, objectMapper.writeValueAsString(userInfo),
                        YFConfig.TOKEN_OUTTIME);
                return ResponseResult.success(photoUrl);
            }
            return ResponseResult.fail();
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult checkPayTransferInfoByMap(Map<Object, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExistToken) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                // 获取user信息
                String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
                // String转object
                UserInfoDTO dto = mapper.readValue(userinfo, UserInfoDTO.class);
                String userId = dto.getUser().getUserId();
                // 收款人账号
                String payeeAccount = (String) map.get("payeeAccount");
                UserInfoVO rpcUserInfo = this.baseMapper.queryUserId(payeeAccount);
                if (rpcUserInfo == null) {
                    return ResponseResult.fail(BizCodeEnume.ACCOUNT_IS_NOT_EXIST);
                } else if (userId.equals(rpcUserInfo.getUserId())) {
                    return ResponseResult.fail(BizCodeEnume.DANGEROUS_TRANSFER_OF_ACCOUNT);
                } else {
                    return ResponseResult.success(rpcUserInfo);
                }
            } catch (Exception e) {
                logger.info("yfPayForTransferCheckPayeeInfoErrorResults：" + e.getMessage());
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult getUcenterSettingByUserId(Map<String, String> param) {
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + param.get("token"));
        UserSettingVO ucenterSettingInfo = this.baseMapper.getUcenterSettingByUserId(userId);
        if (null == ucenterSettingInfo) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.QUERY_USER_FAIL.getMsg());
        }
        if (null != ucenterSettingInfo.getUserLastloginIp() && !"".equals(ucenterSettingInfo.getUserLastloginIp())) {
            RestTemplate restTemplate = new RestTemplate();
            // 获取ip对应城市
            try {
                if(!"0".equals( ucenterSettingInfo.getUserProvinceid()) && !"0".equals(ucenterSettingInfo.getUserCityid()) && !"0".equals(ucenterSettingInfo.getUserAreaid()) ){
                    String country =  baseServiceClient.queryProvinceport(ucenterSettingInfo.getUserProvinceid());
                    String city = baseServiceClient.queryProvinceport(ucenterSettingInfo.getUserCityid());
                    String region = baseServiceClient.queryProvinceport(ucenterSettingInfo.getUserAreaid());
                    ucenterSettingInfo.setUserLastloginArea(
                            country + " " + city + " " + region);
                }

            } catch (Exception e) {
                return ResponseResult.fail();
            }
        }
        return ResponseResult.success(ucenterSettingInfo);
    }

    /**
     * 检测验证码是否正确和更换绑定手机
     *
     * @param paraMap
     * @return
     */
    @Override
    public ResponseResult updateUserMobile(Map<String, String> paraMap) {
        String phoneCode = paraMap.get("phoneCode");
        String userMobile = paraMap.get("userMobile");
        String redisPhoneCode = RedisUtil.get(userMobile);
        if (!phoneCode.equals(redisPhoneCode)) {
            return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
        }

        String tokenString = paraMap.get("token");
        String userinfoString = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + tokenString);
        UserInfoDTO dto = JSON.parseObject(userinfoString, UserInfoDTO.class);
        if (dto == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        UserInfoVO userInfo = dto.getUser();
        String oldUserMobilePhone = userInfo.getUserMobile();
        paraMap.put("oldUserMobilePhone", oldUserMobilePhone);
        if (StringUtils.isEmpty(oldUserMobilePhone)) {
            return ResponseResult.fail(BizCodeEnume.ORIGINAL_PHONE_NUMBER_IS_EMPTY);
        }

        Boolean torf = updateUserBindConnectByUserMobile(paraMap);
        if (torf) {
            UserInfoVO userInfoMapper = this.baseMapper.getUserInfoByPhoneNumber(userMobile);
            Map<String, String> shopMap = new HashMap<>();
            shopMap.put("userId", userInfo.getUserId() + "");
            ResponseResult status = businessServiceClient.queryShopStatus(shopMap);
            if (null != status.getData()) {
                userInfoMapper.setIsShop(CommonType.commonStatus.YES.getCode());
            } else {
                userInfoMapper.setIsShop(CommonType.commonStatus.NO.getCode());
            }
            dto.setUser(userInfoMapper);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + tokenString,
                    JSON.toJSONString(dto), 7200);
            return ResponseResult.success(BizCodeEnume.SUCCESSFULLY_CHANGED_THE_PHONE_NUMBER.getMsg());
        }
        return ResponseResult.success(BizCodeEnume.FAILED_CHANGED_THE_PHONE_NUMBER.getMsg());
    }

    @Override
    public ResponseResult qrUser(Map<String, String> paraMap) throws NotFoundException, IOException, WriterException {
        String token = paraMap.get("token");
        UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
        String userId = userInfo.getUserId().toString();
        String url =YFConfig.QR_CODE_REGISTER_USERID + userId;
        String baseString = QRCodeUtil.text2Base64Str(url);
        Map<String, String> returnMap = new HashMap<String, String>();
        returnMap.put("url", url);
        returnMap.put("baseString", baseString);
        return ResponseResult.success(returnMap);
    }

    @Override
    public ResponseResult myCustomer(Map<String, Object> paraMap) throws JsonParseException, JsonMappingException, IOException, NotFoundException, WriterException {

        String token = paraMap.get("token").toString();
        UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
        String shopId = userInfo.getShopId().toString();
        paraMap.put("shopId", shopId);
        Map map = null;
        try {
            map = ParseMapUtils.beanToMap(paraMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<MyCustomerVO> page=this.baseMapper.listCustomerByShopId(new Query<MyCustomerVO>().getPage(map),
                paraMap);
        List<MyCustomerVO> listCustomerByShopId = page.getRecords();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (MyCustomerVO myCustomer : listCustomerByShopId) {
            Long time = new Long(myCustomer.getUserRegTime());
            String d = sdf.format(time * 1000);
            myCustomer.setUserRegTime(d);

        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("listCustomerByShopId", listCustomerByShopId);
        returnMap.put("countListCustomerByShopId",page.getTotal());
        return ResponseResult.success(returnMap);
    }

    @Override
    public ResponseResult getUserInfo(Map<String, Object> paraMap) throws JsonParseException, JsonMappingException, IOException {
        String token = String.valueOf(paraMap.get("token"));
        UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
        UserInfoForUpdateVO userInfoVo = this.baseMapper.getUserInfo(userInfo.getUserId());

        Map<String, Object> memberClassIdByUserId = baseServiceClient.queryMemberShipGradeByUserId(userInfo.getUserId());
        if(null != memberClassIdByUserId) {
            if(null != memberClassIdByUserId.get("grade_name")) {
                userInfoVo.setMemberName(memberClassIdByUserId.get("grade_name").toString());
            }
            if(null != memberClassIdByUserId.get("grade_url")){
                userInfoVo.setMemberUrl(memberClassIdByUserId.get("grade_url").toString());
            }
        }

        return ResponseResult.success(userInfoVo);
    }

    @Override
    public ResponseResult updateUserInfo(Map<String, String> map) throws ParseException {
        String token = map.get("token");
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String userBirth = null;
        try {
            if (null != map.get("userBirth") && !"".equals(map.get("userBirth"))) {
                String[] dateStrs = map.get("userBirth").split("-");
                for (int i = 0; i < dateStrs.length; i++) {
                    if (dateStrs[i].length() == 1) {
                        dateStrs[i] = "0".concat(dateStrs[i]);
                    }
                }
                String fomDate = dateStrs[0] + "-" + dateStrs[1] + "-" + dateStrs[2];
                Date date = simpleDateFormat.parse(fomDate);
                userBirth = simpleDateFormat.format(date);
            }
            map.put("userBirth", userBirth);
            Integer one = this.baseMapper.update(null, new LambdaUpdateWrapper<UserInfoEntity>()
                    .eq(UserInfoEntity::getUserId, userId)
                    .set(UserInfoEntity::getUserNickname, map.get("userNickname")));
            Integer two = userInfoDetailMapper.update(null, new LambdaUpdateWrapper<UserInfoDetaileEntity>()
                    .eq(UserInfoDetaileEntity::getUserId, userId)
                    .set(UserInfoDetaileEntity::getUserBirth, userBirth)
                    .set(UserInfoDetaileEntity::getUserTruename, map.get("userTruename"))
                    .set(UserInfoDetaileEntity::getUserGender, map.get("userGender")));

            Boolean three = userBindConnectService.update(null, new LambdaUpdateWrapper<UserBindConnectEntity>()
                    .eq(UserBindConnectEntity::getUserId, userId)
                    .set(UserBindConnectEntity::getBindNickname, map.get("userNickname")));

            if (one > 0 && two > 0 && three) {
                String userInfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
                UserInfoDTO dto = JSON.parseObject(userInfo, UserInfoDTO.class);
                UserInfoVO ui = dto.getUser();
                ui.setUserNickname(map.get("userNickname"));
                dto.setUser(ui);
                RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(dto), YFConfig.TOKEN_OUTTIME);
                return ResponseResult.success();
            }
            return ResponseResult.fail();
        } catch (Exception e) {

            return ResponseResult.fail(e.getMessage());
        }

    }

    @Override
    public Integer checkRepeateUserAccount(Map<String, Object> map) {
        int count = 0;
        if (null != map && null != map.get("userMobile")) {
            count = this.baseMapper.selectCount(new QueryWrapper<UserInfoEntity>().eq("user_mobile", map.get("userMobile")).between("user_state", "0", "2"));

        }
        return count;
    }

    @Override
    public ResponseResult forgotPassword(Map<String, Object> map) throws IOException {

        String userMobile = map.get("userMobile").toString();
        String shopId = String.valueOf(map.get("shopId"));
        int checkuserId = checkRepeateUserAccount(map);
        //判断手机号码是否存在
        if (checkuserId == CommonType.commonStatus.NO.getCode()) {

            return ResponseResult.fail(BizCodeEnume.PHONE_EXSIT_EXCEPTION);
        }
        String phoneCode = map.get("phoneCode").toString();
        String redisPhoneCode = RedisUtil.get(userMobile);
        if (!phoneCode.equals(redisPhoneCode)) {
            return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
        }
        if (map.get("password") == null || "".equals(map.get("password"))) {
            return ResponseResult.fail(BizCodeEnume.PASSWORD_CANNOT_BE_EMPTY);
        }
        String password = map.get("password").toString();

        //查询旧密码
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("userMobile",userMobile);
        hashMap.put("shopId",shopId);
        String oldPassword = this.baseMapper.selectOldPasswordByUserMobile(hashMap);


        //输入密码不能和原密码相同
        if (PasswordUtils.BCryptPasswordMatches(password, oldPassword)) {
            return ResponseResult.fail(BizCodeEnume.PASSWORD_CANNOT_BE_OLD_PASSWORD);
        }
        Map<String, String> daoMap = new HashMap<String, String>();
        daoMap.put("userMobile", userMobile);
        daoMap.put("password", PasswordUtils.BCryptPasswordEncoder(password));
        //修改密码
        ResponseResult torf = updateUserInfoByMap(daoMap);

        if (torf.getCode() == CommonStatusEnum.SUCCESS.getCode()) {
            return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(), BizCodeEnume.PASSWORD_UPDATED_SUCCESSFULLY.getMsg());
        } else {
            return ResponseResult.fail(BizCodeEnume.PASSWORD_UPDATED_FAILED);
        }
    }

    @Override
    public ResponseResult checkPhone(Map<String, Object> map) {
        Map<String,Object> result = new HashMap<>();
        if(map.get("token") != null && map.get("token") != "") {

            String jsonUserinfo = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + map.get("token").toString());// 获取user信息
            if (null == jsonUserinfo || jsonUserinfo.equals("")) {
                result.put("start",2);
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getMsg(),result);
            }
            //校验登录名下是否：1.注册；2.有店铺；3有门店
            //根据手机号查用户表是否存在
            // 5 用户未注册  1 用户注册且无店铺 2 已有店铺
            Map<String, String> param = new HashMap<>();
            param.put("phone", map.get("userMobile").toString());
            param.put("shopType", "");
            ResponseResult rr = queryPhoneNumCount(param);
            if(null != rr && BizCodeEnume.USER_DOES_NOT_EXIST.getCode() == rr.getCode() && rr.getMessage().equals(BizCodeEnume.USER_DOES_NOT_EXIST.getMsg())){
                result.put("start",5);
                return ResponseResult.fail(0, "未注册账号",result);
            }else if (null != rr && BizCodeEnume.USER_HAS_OPENED_A_STORE.getCode() == rr.getCode()){
                result.put("start",2);
                return ResponseResult.fail(rr.getMessage(), result);
            }
            //查询用户密码
            String userPwd = this.baseMapper.selectOne(new LambdaQueryWrapper<UserInfoEntity>()
                    .eq(UserInfoEntity::getUserMobile,map.get("userMobile").toString())
                    .isNull(UserInfoEntity::getShopId)).getPassword();
            //根据手机号查门店表
            Integer gataPhoneNum = this.baseMapper.queryGatePhoneNumCount(map.get("userMobile").toString());
            if (gataPhoneNum > 0) {
                result.put("start",2);
                return ResponseResult.fail(BizCodeEnume.REGISTERED_STORE_WITH_PHONE_NUMBER.getMsg(),result);
            }
            result.put("start",1);
            if (userPwd != null && !userPwd.isEmpty()){
                result.put("password",userPwd);
            }else{
                result.put("password","");
            }
            return ResponseResult.success(result);
        }else{
            result.put("start",10086);
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getMsg(),result);
        }
    }

    @Override
    public ResponseResult checkPhoneByBusiness(Map<String, Object> map) {
        Map<String,Object> result = new HashMap<>();
        if(map.get("token") != null && map.get("token")  != "") {
            //根据Token获取用戶信息(shopId)
            String jsonUserinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + map.get("token").toString());
            if (null == jsonUserinfo || jsonUserinfo.equals("")) {
                result.put("start",2);
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            // 获取user信息
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken( map.get("token").toString());

            //校验登录名下是否：1.注册；2.有店铺；3有门店
            //根据手机号查用户表是否存在
            Map<String, String> param = new HashMap<>();
            param.put("phone",map.get("phone").toString());
            param.put("shopType", String.valueOf(userInfo.getShopType()));
            param.put("shopId", String.valueOf(userInfo.getShopId()));
            ResponseResult rr = queryPhoneNumCount(param);
            if(null == rr || CommonStatusEnum.SUCCESS.getCode() != rr.getCode()){
                result.put("start",2);
                return ResponseResult.fail(rr.getMessage(), result);
            }
            //根据手机号查门店表
            //判断是否为品牌店铺
            Integer gataPhoneNum = 0;
            if (userInfo.getShopType() == 3){
                //走品牌店铺
                gataPhoneNum = this.baseMapper.queryGatePhoneNumCount1(map.get("phone").toString(),userInfo.getShopId());
            }else{
                gataPhoneNum = this.baseMapper.queryGatePhoneNumCount(map.get("phone").toString());
            }

            if (gataPhoneNum > 0) {
                result.put("start",2);
                return ResponseResult.fail(BizCodeEnume.REGISTERED_STORE_WITH_PHONE_NUMBER);
            }
            result.put("start",1);
            return ResponseResult.success(result);
        }else{
            result.put("start",2);
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult queryAuditList(Map<String, Object> param) {
        try {
            IPage<BusinessUserListVO> page = this.baseMapper.queryAuditList(new Query<BusinessUserListVO>().getPage(param), param);
            return ResponseResult.success(PageUtils.getPage(page));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
        }
    }

    @Override
    public ResponseResult auditPass(Map<String, Object> param) {
        try {
            Integer isPass = (Integer) param.get("isPass");
            if (null == param.get("userId") || "".equals(param.get("userId"))) {
                return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER.getCode(),BizCodeEnume.MISSING_PARAMETER.getMsg());
            }
            UserInfoEntity info = this.baseMapper.selectOne(new LambdaQueryWrapper<UserInfoEntity>()
                    .eq(UserInfoEntity::getUserId, param.get("userId")));
            Map<String,Object> map = new HashMap<>();
            //审核通过
            if (1 == isPass) {
                param.put("isApproved", 1);
                param.put("userState", 2);
                this.baseMapper.updateBusinessUserStatus(param);
                this.baseMapper.updateUserInfoStatus(param);
                // 企业审核通过
                map.put("result2","成功");
                //审核不通过
            } else if (0 == isPass) {
                param.put("isApproved", 2);
                param.put("userState", 0);
                this.baseMapper.updateBusinessUserStatus(param);
                this.baseMapper.updateUserInfoStatus(param);
                deleteAccount(param);
                // 企业审核不通过
                map.put("result2","失败，失败原因："+param.get("auditCommnet"));

            }
            map.put("userMobile",info.getUserMobile());
            map.put("result1",info.getUserName());
            map.put("smstype",1);
            thirdPartyServiceClient.storeQualification(map);
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
        }
    }

    @Override
    public ResponseResult userCount(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                // 类型:1、全部，2、当日，3、本周，4、本月，5、年度
                Integer type = (Integer) map.get("type");
                Integer userCount = 0;
                if (type == 1) {
                    userCount = this.baseMapper.queryAllUserCount();
                } else if (type == 2) {
                    userCount = this.baseMapper.queryTodayUserCount();
                } else if (type == 3) {
                    userCount = this.baseMapper.queryWeekUserCount();
                } else if (type == 4) {
                    userCount = this.baseMapper.queryMonthUserCount();
                } else {
                    userCount = this.baseMapper.queryYearUserCount();
                }
                return ResponseResult.success(userCount);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult userTodayNumber(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                Integer userCount  = this.baseMapper.queryTodayUserCount();
                return ResponseResult.success(userCount);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult updateMemberLoginPassword(Map<String, Object> param) {
        if (RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + param.get("token"))) {

            String password=PasswordUtils.BCryptPasswordEncoder(param.get("password").toString());
            this.baseMapper.update(null,new LambdaUpdateWrapper<UserInfoEntity>()
                            .set(UserInfoEntity::getPassword,password)
                            .eq(UserInfoEntity::getUserId,param.get("userId")));
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult updateUser(Map<String, Object> paraMap) {
        UpdateWrapper<UserInfoEntity> updateWrapper = new UpdateWrapper<>();

        if (null != paraMap && null != paraMap.get("userId")) {
            updateWrapper.eq("user_id", paraMap.get("userId"));
        }
        if (null != paraMap && null != paraMap.get("userIntegral")) {
            updateWrapper.set("user_integral", paraMap.get("userIntegral"));
        }
        this.baseMapper.update(null,updateWrapper);
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryUserTurePort(Map<String, Object> paraMap) {
        IPage<MemberMessageListVO> page=this.baseMapper.queryUserTurePort(new Query<MemberMessageListVO>().getPage(paraMap),
                paraMap);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryShareUserListPort(Map<String, Object> param) {

        String userId =this.baseMapper.selectOne(new LambdaQueryWrapper<UserInfoEntity>()
                       .eq(param.containsKey("userName"),UserInfoEntity::getUserName,param.get("userName").toString())
                       .eq(param.containsKey("userMobile"),UserInfoEntity::getUserMobile,param.get("userMobile").toString())
                       .last("limit 1")).getUserId();
        if(null==userId&&"".equals("")){
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }
        param.put("shareUserId",userId);
        IPage<MemberMessageListVO> page=this.baseMapper.queryShareUserListPort(new Query<MemberMessageListVO>().getPage(param),
                param);
        for (MemberMessageListVO res : page.getRecords()) {
            if (null != res.getUserRegTime()) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Long time = new Long(res.getUserRegTime());
                String d = format.format(time * 1000);
                res.setUserRegTime(d);
            }
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult updateMemberMessageDetailPort(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.get("token").toString());
        if (userInfo.getRightsGroupId() == 1) {
            if (param.containsKey("userPayPasswd")
                    &&param.get("userPayPasswd") != null
                    && !(param.get("userPayPasswd") .equals(""))
                    && !(param.get("userPayPasswd") .equals("******"))) {
                String pass =PasswordUtils.BCryptPasswordEncoder(param.get("userPayPasswd").toString());
                param.put("userPayPasswd",pass);
                this.baseMapper.updateuserPa(param);
            }
            if (param.containsKey("password")
                    &&param.get("password") != null
                    && !(param.get("password") .equals(""))
                    && !(param.get("password") .equals("******"))) {
                String spass =PasswordUtils.BCryptPasswordEncoder(param.get("password").toString());
                this.baseMapper.update(null,new LambdaUpdateWrapper<UserInfoEntity>()
                        .set(UserInfoEntity::getPassword,spass)
                        .eq(UserInfoEntity::getUserId,param.get("userId").toString()));
            }
            this.baseMapper.updateuserInfoPort(param);
            userInfoDetailMapper.updateUcenterInfo(param);

            if(param.get("tags")!=null){
                List<Integer> tags = Collections.singletonList(Integer.valueOf(param.get("tags").toString()));
                String str=StringUtils.join(tags, ",");
                param.put("tagId",str);
                param.put("memberId",param.get("userId").toString());
                this.baseMapper.updateTag(param);
            }

        } else {

            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult updatePersonalBase(UserPersonalBaseVO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            param.setUserId(userInfo.getUserId());
            this.baseMapper.updatePersonalBase(param);
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult updateUserIsShop(String userId, Integer shopId, Integer isShop) {
        this.baseMapper.updateUserIsShop(userId, isShop);
        List<UserSellerBaseVO> list = userSellerBaseService.getSellerBase(shopId);
        if (!list.isEmpty()) {
            for (UserSellerBaseVO userSellerBase : list) {
                this.baseMapper.updateUserIsShop(userSellerBase.getUserId(), isShop);
            }
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult addSeller(Map<String, Object> paraMap) {
        if (StringUtils.isEmpty((String) paraMap.get("shopId"))) {
            return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
        }
        boolean flag;
        //查询是否注册过商户
        UserSellerBaseEntity sellerBase = ParseMapUtils.parseMap2Object(paraMap, UserSellerBaseEntity.class);
        Integer integer = userSellerBaseService.getBaseMapper().selectCount(new LambdaQueryWrapper<UserSellerBaseEntity>()
                .eq(UserSellerBaseEntity::getShopId,  Integer.valueOf(paraMap.get("shopId").toString()))
                .ne(UserSellerBaseEntity::getSellerIsAdmin, 1));
        if (integer > 0) {
            //注册过修改商户信息
            flag = userSellerBaseService.update(sellerBase, new LambdaQueryWrapper<UserSellerBaseEntity>()
                    .eq(UserSellerBaseEntity::getShopId,  Integer.valueOf(paraMap.get("shopId").toString())));
        } else {
            //未注册过新增商户信息
            sellerBase.setRightsGroupId(1);
            sellerBase.setSellerIsAdmin((byte) 1);
            sellerBase.setSellerGroupId(1);
            flag = userSellerBaseService.save(sellerBase);
        }
        if (flag) {
            // 插入成功，更新 用户信息
            String userId = (String) paraMap.get("userId");

            this.update(new LambdaUpdateWrapper<UserInfoEntity>()
                    .set(UserInfoEntity::getShopId, Integer.valueOf(paraMap.get("shopId").toString()))
                    //.set(UserInfoEntity::getIsShop, CommonType.commonStatus.YES.getCode())
                    .eq(UserInfoEntity::getUserId, userId));
            UserInfoVO userInfo = this.baseMapper.getUserInfoByUserIdNoState(userId);
            String token = RedisUtil.get(YFConfig.RANDOM_TOKEN + userId);
            if (token != null) {
                String userInfoStr = RedisUtil.get(YFConfig.LOGIN + userId);
                if (null != userInfoStr) {
                    UserInfoDTO dto = JSON.parseObject(userInfoStr, UserInfoDTO.class);
                    dto.setUser(userInfo);
                    RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(dto), YFConfig.TOKEN_OUTTIME);
                    RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId(), YFConfig.TOKEN_OUTTIME);
                }

            }
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.SHOP_REGISTRATION_FAIL);
    }

    @Override
    public ResponseResult queryUserTrueListPort(Map<String, Object> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(paraMap.get("token").toString());
        if (null != userInfo) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (paraMap.containsKey("finishTime") && !"".equals(paraMap.containsKey("startTime"))) {
                Long finishTime = null;
                Long startTime = null;
                try {
                    String finishTime1 = paraMap.get("finishTime").toString();
                    String startTime1 = paraMap.get("startTime").toString();
                    if (!StringUtils.isEmpty(finishTime1) && !StringUtils.isEmpty(startTime1)) {
                        finishTime = format.parse(finishTime1).getTime() / 1000;
                        startTime = format.parse(startTime1).getTime() / 1000;
                        paraMap.put("finishTime",finishTime.toString());
                        paraMap.put("startTime",startTime.toString());
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //将对象转换为map
            try {
                //分页查询数据
                IPage<MemberMessageListVO> page = this.baseMapper.queryUserTrueListPort(new Query<MemberMessageListVO>().getPage(paraMap), paraMap);
                for (MemberMessageListVO res : page.getRecords()) {
                    if (null != res.getUserRegTime()) {
                        Long time = new Long(res.getUserRegTime());
                        String d = format.format(time * 1000);
                        res.setUserRegTime(d);
                    }
                }
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryMemberMessageDetailPort(MemberMessageListIntegralDTO dto) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(dto.getToken());
        if (null != userInfo) {
            MemberMessageDetailVO result = this.baseMapper.queryMemberMessageDetailPort(dto.getUserId());
            if (null != result.getUserRegTime()) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Long time = new Long(result.getUserRegTime());
                String d = format.format(time * 1000);
                result.setUserRegTime(d);
            }
//            String address = baseServiceClient.getAddressString(Integer.valueOf(result.getUserProvinceid()),
//                    Integer.valueOf(result.getUserCityid()), Integer.valueOf(result.getUserAreaid())).getData().toString();
//            result.setArea(address);

            String tagId = this.baseMapper.getTagId(dto.getUserId());
            if (StringUtils.isNotBlank(tagId)) {
                String[] split = tagId.split(",");
                List<TagInfoVO> tagList = new ArrayList<>();
                for (String s : split) {
                    TagInfoVO tagInfoByid = this.baseMapper.getTagInfoByid(s);
                    if (null != tagInfoByid) {
                        tagList.add(tagInfoByid);
                        result.setTagInfos(tagList);
                    }
                }
            }
            Integer integer = this.baseMapper.queryMemberMessageListIntegral(dto.getUserId());
            if (integer != null) {
                result.setMemberIntegral(integer);
            }
            //新增企业信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", dto.getToken());
            map.put("userId", dto.getUserId());
            BusinessUserInfoDetailVO detail = userBusinessInfoMapper.queryDetail(map);
            result.setBusinessDetail(detail);
            return ResponseResult.success(result);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryMemberMessageDetailPortEncoded(MemberMessageListIntegralDTO dto) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(dto.getToken());
        if (null != userInfo) {
            MemberMessageDetailVO result = this.baseMapper.queryMemberMessageDetailPort(dto.getUserId());
            if (null != result.getUserRegTime()) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Long time = new Long(result.getUserRegTime());
                String d = format.format(time * 1000);
                result.setUserRegTime(d);
            }
           String address = baseServiceClient.getAddressString(Integer.valueOf(result.getUserProvinceid()),
                   Integer.valueOf(result.getUserCityid()), Integer.valueOf(result.getUserAreaid())).getData().toString();
           result.setArea(address);

            String tagId = this.baseMapper.getTagId(dto.getUserId());
            if (StringUtils.isNotBlank(tagId)) {
                String[] split = tagId.split(",");
                List<TagInfoVO> tagList = new ArrayList<>();
                for (String s : split) {
                    TagInfoVO tagInfoByid = this.baseMapper.getTagInfoByid(s);
                    if (null != tagInfoByid) {
                        tagList.add(tagInfoByid);
                        result.setTagInfos(tagList);
                    }
                }
            }
            Integer integer = this.baseMapper.queryMemberMessageListIntegral(dto.getUserId());
            if (integer != null) {
                result.setMemberIntegral(integer);
            }
            //新增企业信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", dto.getToken());
            map.put("userId", dto.getUserId());
            BusinessUserInfoDetailVO detail = userBusinessInfoMapper.queryDetail(map);
            result.setBusinessDetail(detail);
            String s = Base64.getEncoder().encodeToString(JSONObject.toJSONString(result).getBytes());
            return ResponseResult.success(s);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }


    @Override
    public ResponseResult updateMemberMessageIntegral(MemberMessageListIntegralDTO dto) {
        try {
            if(dto.getIntegral() < 0){
                return ResponseResult.fail(BizCodeEnume.INTEGRAL_CANNOT_BE_LESS_THAN_0);
            }
            if(dto.getUserIdList().size() < 0){
                return ResponseResult.fail(BizCodeEnume.USER_ID_IS_NULL);
            }
            //获取所有用户id
            List<String> userIdList = dto.getUserIdList();
            Integer userIntegral = null;
            UserPointsLogEntity userPointLogParam = new UserPointsLogEntity();
            userPointLogParam.setClassId(5);
            userPointLogParam.setPointsLogTime(new Date());
            userPointLogParam.setPointsLogFlag("reg");
            userPointLogParam.setPointsLogDesc("平台操作");
            userPointLogParam.setPointsLogOperate(dto.getDesc());
            for (String userId : userIdList) {
                //获取当前用户的积分
                userIntegral = this.baseMapper.selectById(userId).getUserIntegral();
                //type 1是增加积分
                if(dto.getType() == 1){
                    Integer temp =userIntegral + dto.getIntegral();
                    this.baseMapper.update(null,new LambdaUpdateWrapper<UserInfoEntity>()
                            .eq(UserInfoEntity::getUserId,userId)
                            .set(UserInfoEntity::getUserIntegral,temp));
                    //类型 1获取积分2积分消费
                    userPointLogParam.setPointsLogType(1);
                    userPointLogParam.setPointsLogPoints(dto.getIntegral());
                    userPointLogParam.setUserId(userId);
                    if(!StringUtils.isNotEmpty(dto.getDesc())){
                        userPointLogParam.setPointsLogOperate("平台添加"+dto.getIntegral()+"积分");
                    }
                    userPointsLogService.save(userPointLogParam);
                }else{
                    //type 0 是扣除积分
                    //如果当前用户的积分 小于 等于 平台扣除的积分直接赋值为 0
                    Integer temp =userIntegral - dto.getIntegral();
                    if(temp <= 0){
                        temp=0;
                    }
                    this.baseMapper.update(null,new LambdaUpdateWrapper<UserInfoEntity>()
                            .eq(UserInfoEntity::getUserId,userId)
                            .set(UserInfoEntity::getUserIntegral,temp));
                    //类型 1获取积分2积分消费
                    userPointLogParam.setPointsLogType(2);
                    userPointLogParam.setPointsLogPoints(dto.getIntegral());
                    userPointLogParam.setUserId(userId);
                    if(!StringUtils.isNotEmpty(dto.getDesc())){
                        userPointLogParam.setPointsLogOperate("平台扣除"+dto.getIntegral()+"积分");
                    }
                    userPointsLogService.save(userPointLogParam);
                }
                //积分修改完成 修改会员等级
                Map<String, Object> map = new HashMap<>();
                map.put("gradeStart", CommonType.commonStatus.YES.getCode());
                map.put("userIntegral", userIntegral);
                map.put("userId", userId);
                baseServiceClient.queryMembershipGradeByGradeRule(map);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryMemberMessageListPortExcel(MemberMessageListDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            String[] title = {"会员名称", "会员ID", "手机号码", "注册时间", "性别", "最后登陆时间", "购买次数", "支付总额"};
            List<Map<String, String>> list = Lists.newArrayList();
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                if (!"".equals(param.getFinishTime()) && !"".equals(param.getStartTime())) {
                    Long finishTime = null;
                    Long startTime = null;
                    try {
                        finishTime = dateformat.parse(param.getFinishTime()).getTime() / 1000;
                        startTime = dateformat.parse(param.getStartTime()).getTime() / 1000;
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    param.setFinishTime(finishTime.toString());
                    param.setStartTime(startTime.toString());
                }
                param.setPage((param.getPage() - 1) * param.getLimit());
                List<MemberMessageListVO> result = this.baseMapper.queryMemberMessageListPortExp(param);
                if (result.size() >= 30000) {
                    return ResponseResult.fail(BizCodeEnume.PLEASE_BE_LESS_THAN_30000_PIECES);
                }
                for (MemberMessageListVO res : result) {
                    if (res.getUserGender() != null) {
                        switch (res.getUserGender()) {
                            default:
                            case "0":
                                res.setUserGender("保密");
                                break;
                            case "1":
                                res.setUserGender("男");
                                break;
                            case "2":
                                res.setUserGender("女");
                                break;
                        }
                    }
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (!StringUtils.isEmpty(res.getUserRegTime())) {
                        Long time = new Long(res.getUserRegTime());
                        String d = format.format(time * 1000);
                        res.setUserRegTime(d);
                    }
                    HashMap<String, String> map = Maps.newHashMap();
                    map.put("会员名称", res.getUserName());
                    map.put("会员ID", res.getUserId() + "");
                    map.put("手机号码", res.getUserMobile() + "");
                    map.put("注册时间", res.getUserRegTime() + "");
                    map.put("性别", res.getUserGender() + "");
                    map.put("最后登陆时间", res.getUserLastloginTime() + "");
                    map.put("购买次数", res.getOrderCount() + "");
                    map.put("支付总额", res.getSumAmount() + "");

                    list.add(map);
                }
                // excel文件名
                Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
                 * 该list为每个sheet页的数据
                 */> map = Maps
                        .newHashMap();
                map.put("测试合并数据", list);
                String url = ExcelsUtil.createExcel(title, map,
                        new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
                return ResponseResult.success(url);
            }catch (Exception e){
                logger.info(e.getMessage());
                return ResponseResult.fail(e.getMessage());
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryMemberMessageListPort(MemberMessageListDTO dto) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(dto.getToken());
        if (null != userInfo) {
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (!"".equals(dto.getFinishTime()) && !"".equals(dto.getStartTime())) {
                    Long finishTime = null;
                    Long startTime = null;
                    try {
                        finishTime = format.parse(dto.getFinishTime()).getTime() / 1000;
                        startTime = format.parse(dto.getStartTime()).getTime() / 1000;
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    dto.setFinishTime(finishTime.toString());
                    dto.setStartTime(startTime.toString());
                }
                IPage<MemberMessageListVO> page;
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(dto);
                //查询平台会员列表
                String shopId = String.valueOf(dto.getShopId());
                if (shopId.equals("null")|| shopId.isEmpty()){
                    page = this.baseMapper.queryMemberMessageListPort(new Query<MemberMessageListVO>().getPage(data), dto);
                }else{
                    page = this.baseMapper.queryMemberMessageListPort1(new Query<MemberMessageListVO>().getPage(data), dto);
                }
                List<MemberMessageListVO> records = page.getRecords();
                if (!records.isEmpty()) {
                    for (MemberMessageListVO result : records) {
                        if (null != result.getUserRegTime()) {
                            Long time = new Long(result.getUserRegTime());
                            String d = format.format(time * 1000);
                            result.setUserRegTime(d);
                        }
                        //获取会员等级
                        MembershipGradeVO membershipGrade = new MembershipGradeVO();
                        membershipGrade.setId(result.getMemberClassId());
                        List<MembershipGradeVO> membershipGrades = this.baseMapper.queryMembershipGradeById(membershipGrade);
                        if (membershipGrades != null && !membershipGrades.isEmpty()) {
                            result.setMemberClass(membershipGrades.get(0).getGradeName());
                        }
                        //获取会员标签
                        String tagId = result.getTagId();
                        if (StringUtils.isNotBlank(tagId)) {
                            String[] split = tagId.split(",");
                            List<String> tagList = new ArrayList<>();
                            for (String s : split) {
                                TagInfoVO tagInfoByid = this.baseMapper.getTagInfoByid(s);
                                if (null != tagInfoByid) {
                                    tagList.add(tagInfoByid.getTagName());
                                    result.setTagList(tagList);
                                }
                            }
                        }
                    }
                }
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    /**
     * 删除用户信息
     */
    private void deleteAccount(Map<String, Object> param){
        this.baseMapper.deleteUserInfo(param);
        this.baseMapper.deleteUserDetailInfo(param);
        this.baseMapper.deleteUserBindConnect(param);
        this.baseMapper.deleteUserSellerBase(param);
        this.baseMapper.deleteShopVipUser(param);
        this.baseMapper.deleteShopVkApply(param);
        this.baseMapper.deleteShopVkUser(param);
        this.baseMapper.deleteBusinessInfo(param);
    }

    public ResponseResult queryPhoneNumCount(Map<String, String> paraMap){
        String phone = paraMap.get("phone");
        //根据手机号判断当前用户是否注册
        String userId = null;

        userId = this.baseMapper.queryPhoneNumCount(phone);
        if (null == userId) {
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }
        //查询当前用户是否开通店铺 或者是其他店铺的子账号
        Integer shopCount = userSellerBaseService.count(new LambdaQueryWrapper<UserSellerBaseEntity>()
                            .eq(UserSellerBaseEntity::getUserId,userId));
        //查询当前用户是否有正在开通店铺
        Integer shopJoinBase = this.baseMapper.queryShopJoinBase(userId);
        if((0 == shopCount) && (null == shopJoinBase || 0 == shopJoinBase)){

            return ResponseResult.success(BizCodeEnume.USER_HAS_NOT_OPENED_A_STORE);
        }else {
            return ResponseResult.fail(BizCodeEnume.USER_HAS_OPENED_A_STORE);
        }
    }

    @Override
    public ResponseResult feginAddpointsLog(UserPointLogDTO param) {
        Integer integer = this.baseMapper.addPointsLog(param);
        if (integer > 0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }

    @Transactional
    public Boolean updateUserBindConnectByUserMobile(Map<String, String> paraMap) {

        Integer userInfoInteger = this.baseMapper.update(null, new LambdaUpdateWrapper<UserInfoEntity>()
                .eq(UserInfoEntity::getUserMobile, paraMap.get("oldUserMobilePhone"))
                .set(UserInfoEntity::getUserMobile, paraMap.get("userMobile")));

        String oldBindId = "mobile_" + paraMap.get("oldUserMobilePhone");
        paraMap.put("oldBindId", oldBindId);
        String newBindId = "mobile_" + paraMap.get("userMobile");
        paraMap.put("newBindId", newBindId);
        Boolean userBindInteger = userBindConnectService.update(null, new LambdaUpdateWrapper<UserBindConnectEntity>()
                .eq(UserBindConnectEntity::getBindId, oldBindId)
                .set(UserBindConnectEntity::getBindId, newBindId));

        return 1 == userInfoInteger && userBindInteger;
    }


    public Boolean uploadPhoto(String userId, String photoUrl) {

        Boolean torf = userInfoDetailService.update(null, new LambdaUpdateWrapper<UserInfoDetaileEntity>()
                .eq(UserInfoDetaileEntity::getUserId, userId)
                .set(UserInfoDetaileEntity::getUserAvatar, photoUrl));
        Boolean torf2 = userBindConnectService.update(null, new LambdaUpdateWrapper<UserBindConnectEntity>()
                .eq(UserBindConnectEntity::getUserId, userId).set(UserBindConnectEntity::getBindAvator, photoUrl));
        return torf2;
    }

    @Override
    public ResponseResult queryShopUserInfo(Integer shopId) {
        UserInfoVO userInfoVO = this.baseMapper.queryShopUserInfo(shopId);
        return ResponseResult.success(userInfoVO);
    }

    @Override
    public ResponseResult updateArticleUserInfo(Map<Object, Object> param) {
        UserInfoVO info = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        param.put("userId",info.getUserId());
        this.baseMapper.updateArticleUserInfo(param);
        return ResponseResult.success();
    }

    @Override
    public UserInfoVO getUserInfoByPhoneNum(Map<String, String> checkPhoneMap) {
        return this.baseMapper.getUserInfoByPhoneNum(checkPhoneMap);
    }

    @Override
    public ResponseResult updateUserNickNameavAtarUrl(Map<String, Object> updateUserParam) {
        this.baseMapper.updateUserNickName(updateUserParam);
        userBindConnectService.updateUserNickNameavAtarUrl(updateUserParam);
        userInfoDetailService.updateUserAtarUrl(updateUserParam);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult thirDregister(Map<String, String> map) throws UnknownHostException, TransactionException {

        logger.info("paraMap{}", JSON.toJSONString(map));
        String openid = map.get("openid");
        String nickname = map.get("nickName");
        String avatarUrl = map.get("avatarUrl");
        String shopId = map.get("shopId");
        String userMobile = map.get("userMobile");
        String bindType = map.get("bindType");
        String bindId = map.get("bindId");

        Map<String, String> checkPhoneMap = new HashMap<>();
        checkPhoneMap.put("userMobile", userMobile);
        String checkuserId = null;
        if (shopId != null) {
            checkPhoneMap.put("shopId", shopId);
        }
        //查询平台用户或者品牌店铺用户信息
        UserInfoVO user = this.baseMapper.queryUserId(userMobile);
        if(null != user){
            checkuserId = user.getUserId();
        }
        UserInfoDTO dto = new UserInfoDTO();
        if (null != checkuserId && !checkuserId.isEmpty()) {
            Map<String, Object> userThreeBindMap = new HashMap<>();
            userThreeBindMap.put("bindId", bindId);
            // 这个是qq或者微信绑定，2:qq 3:weixin7微信小程序
            userThreeBindMap.put("bind_type", bindType);
            userThreeBindMap.put("bind_nickname", nickname);
            userThreeBindMap.put("bind_avator", avatarUrl);
            userThreeBindMap.put("bind_openid", openid);
            userThreeBindMap.put("bind_unionid", openid);
            userThreeBindMap.put("user_id", checkuserId);
            userBindConnectService.insertUserThreeBindMap(userThreeBindMap);
            //查询平台用户或者品牌店铺用户信息
            UserInfoVO userInfo = this.baseMapper.getUserInfoByPhoneNum(checkPhoneMap);

            // 如果没有shopId 就去查找 门店id 赋值
            if (null == userInfo.getShopId() && null != userInfo.getUserMobile()) {
                Map<String, String> gateMap = new HashMap<>();
                gateMap.put("userId",userInfo.getUserId());
                //查询是否正常商家
                ResponseResult shopResult = businessServiceClient.queryGateShopIdByUserId(gateMap);
                if (null != shopResult.getData()) {
                    Map<String, String> shopMap = (Map<String, String>) shopResult.getData();
                    userInfo.setShopId(shopMap.get("shopGateId"));
                }
            }

            // paymentServiceClient.createUser(userInfo.getUserId());
            String token = JwtUtil.createJWT(userInfo.getUserId());
            dto.setUser(userInfo);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(dto),
                    YFConfig.TOKEN_OUTTIME);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId(),
                    YFConfig.TOKEN_OUTTIME);

            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("token", token);
            returnMap.put("userId", userInfo.getUserId());
            returnMap.put("userMobile", userInfo.getUserMobile());
            returnMap.put("platForm", bindType);

            //更新用户活跃度
            userLiveStatisticsService.saveLiveStatistics(returnMap);

            //先注册pc后登录小程序 小程序 头像 昵称 覆盖pc
            Map<String, Object> updateUserParam = new HashMap<>();
            updateUserParam.put("userId", userInfo.getUserId());
            updateUserParam.put("avatarUrl", avatarUrl);
            updateUserParam.put("nickname", nickname);
            updateUserNickNameavAtarUrl(updateUserParam);

            //判断当前用户当天是否已经登录过，登录过不添加积分
            memberPointsService(userInfo);
            return ResponseResult.success(token);
        } else {
            //用户信息
            UserInfoEntity record = new UserInfoEntity();
            record.setUserMobile(userMobile);
            record.setPassword("");
            record.setUserLastloginTime(DateUtils.getNowDateToDf());
            record.setUserName(nickname);
            record.setUserNickname(nickname);
            record.setShopId((shopId != null && !shopId.isEmpty()) ? Integer.parseInt(shopId) : null);
            record.setUserLastloginIp(IpUtils.getIpAddress());

            //用户详情
            UserInfoDetaileEntity insertUserInfoDetail = new UserInfoDetaileEntity();
            insertUserInfoDetail.setUserRegTime(System.currentTimeMillis() / 1000);
            insertUserInfoDetail.setUserRegIp(IpUtils.getIpAddress());
            insertUserInfoDetail.setUserPlatform(Integer.valueOf(bindType));
            insertUserInfoDetail.setUserAvatar(avatarUrl);

            //手机号绑定信息
            UserBindConnectEntity userBindMap = new UserBindConnectEntity();
            String bindUserMobile = (shopId != null && !shopId.isEmpty()) ? "mobile_" + "_" + shopId : "mobile_" + userMobile;
            userBindMap.setBindId(bindUserMobile);
            // 这个是手机绑定，必须为12
            userBindMap.setBindType(Byte.parseByte("12"));

            //openId绑定信息
            UserBindConnectEntity userBindOpenidMap = new UserBindConnectEntity();
            userBindOpenidMap.setBindId(bindId);
            // 这个是qq或者微信绑定，2:qq 3:weixin7微信小程序
            userBindOpenidMap.setBindType(Byte.parseByte(bindType));
            userBindOpenidMap.setBindNickname(nickname);
            userBindOpenidMap.setBindAvator(avatarUrl);
            userBindOpenidMap.setBindOpenid(openid);
            userBindOpenidMap.setBindUnionid(openid);

            // 向积分表插入积分
            UserPointsLogEntity userPointLog = new UserPointsLogEntity();
            userPointLog.setPointsLogType(CommonType.pointsLogType.GAIN.getCode());
            userPointLog.setClassId(CommonType.pointType.REGISTRATION.getCode());
            userPointLog.setPointsLogTime(new Date());
            userPointLog.setPointsLogDesc(BizCodeEnume.MEMBER_REGISTRATION.getMsg());
            userPointLog.setPointsLogFlag("reg");

            //雪花算法生成用户id
            String userId = SnowflakeIdWorker.getSnowId();
            Boolean bool = insertThreeInfoTwo(record, insertUserInfoDetail, userBindMap, userPointLog,
                    userBindOpenidMap,userId);
            if (!bool) {
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                return ResponseResult.fail(BizCodeEnume.REGISTRATION_FAIL);
            }
            String token = JwtUtil.createJWT(record.getUserId());
            UserInfoVO userInfo = this.baseMapper.getUserInfoByPhoneNum(checkPhoneMap);
            paymentServiceClient.createUser(record.getUserId());
            // 如果没有shopId 就去查找 门店id 赋值
            if (null == userInfo.getShopId() && null != userInfo.getUserMobile()) {
                Map<String, String> gateMap = new HashMap<>();
                gateMap.put("userId",userInfo.getUserId());
                //查询是否正常商家
                ResponseResult shopResult = businessServiceClient.queryGateShopIdByUserId(gateMap);
                if (null != shopResult.getData()) {
                    Map<String, String> shopMap = (Map<String, String>) shopResult.getData();
                    userInfo.setShopId(shopMap.get("shopGateId"));
                }
            }
            dto.setUser(userInfo);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(dto),
                    YFConfig.TOKEN_OUTTIME);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId(),
                    YFConfig.TOKEN_OUTTIME);
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("token", token);
            returnMap.put("userId", userInfo.getUserId());
            returnMap.put("userMobile", userInfo.getUserMobile());
            returnMap.put("platForm", bindType);

            //更新用户活跃度
            userLiveStatisticsService.saveLiveStatistics(returnMap);
            return ResponseResult.success(token);
        }

    }

    public Boolean insertThreeInfoTwo(UserInfoEntity userinfo, UserInfoDetaileEntity insertUserInfoDetail,
                                      UserBindConnectEntity userBindMap, UserPointsLogEntity userPointLog,
                                      UserBindConnectEntity userBindOpenidMap, String userId) {
        try {
            //查询积分规则
            ResponseResult resultResp = baseServiceClient.queryIntegralRules();
            Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();

            userinfo.setUserId(userId);
            userinfo.setUserName(userinfo.getUserMobile());
            userinfo.setUserCountLogin(1);
            userinfo.setUserIsNew(CommonType.commonStatus.YES.getCode());
            userinfo.setUserIntegral(integralRules.get("ruleRegister"));
            //保存用户
            int one = this.baseMapper.insert(userinfo);


            if(null == insertUserInfoDetail.getUserAvatar()){
                ResponseResult avatorMap = baseServiceClient.selectByConfigKey("photo_user_logo");
                Map<String, Object> configMap = (Map<String, Object>) avatorMap.getData();
                String userAvator = configMap.get("configValue").toString();
                insertUserInfoDetail.setUserAvatar(userAvator);
            }
            insertUserInfoDetail.setUserId(userId);
            insertUserInfoDetail.setCreateUser(userinfo.getUserMobile());
            insertUserInfoDetail.setUserMobileVerify(1);
            //保存用户详情
            Boolean two= userInfoDetailService.save(insertUserInfoDetail);


            userBindMap.setUserId(userId);
            userBindMap.setCreateUser(userinfo.getUserMobile());
            //保存用户绑定表  手机号  openid
            Boolean three  = userBindConnectService.save(userBindMap);
            userBindOpenidMap.setUserId(userId);
            Boolean five  = userBindConnectService.save(userBindOpenidMap);


            //添加积分变更表
            userPointLog.setUserId(userId);
            userPointLog.setPointsLogPoints(integralRules.get("ruleRegister"));
            userPointLog.setPointsLogOperate("会员注册");
            Boolean four = userPointsLogService.save(userPointLog);

            //修改会员等级
            Map<String, Object> gradeMap = new HashMap<>();
            gradeMap.put("ruleRegister", integralRules.get("ruleRegister"));
            gradeMap.put("userId", userId);
            ResponseResult result = baseServiceClient.saveTagClass(gradeMap);

            UserInfoVO ui = new UserInfoVO();
            ui.setUserId(userId);
            LoginContext context = new LoginContext(ui);
            LoginContext.binding(context);

            //判断是否添加成功
            if (CommonType.commonStatus.YES.getCode() == one
                    && two
                    && three
                    && four
                    && five
                    && CommonStatusEnum.SUCCESS.getCode() == result.getCode()) {
                RedisUtil.set(YFConfig.YF_USER_LOGON_USERID + userinfo.getUserMobile(), userId);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return false;
        }
    }

    //用户会员,积分,等级方法
    public void memberPointsService(UserInfoVO userInfo) {
        //判断当前用户当天是否已经登录过，登录过不添加积分
        Map<String, String> param = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        param.put("startTime", sdf.format(DateUtils.getStartTime()));
        param.put("endTime", sdf.format(DateUtils.getEndTime()));
        param.put("userId", userInfo.getUserId());
        param.put("classId", "2");

        ResponseResult data = userPointsLogService.queryLoginExit(param);


        if(data.getData() == null) {
            //查询积分规则
            ResponseResult resultResp = baseServiceClient.queryIntegralRules();
            Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();
            //修改会员积分和会员等级
            MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
            ArrayList<String> list = new ArrayList<>();
            list.add(userInfo.getUserId());
            updateMemberMessageListIntegral.setUserIdList(list);
            updateMemberMessageListIntegral.setIntegral(integralRules.get("ruleLogin"));
            //1是增加积分 0 是扣除积分
            updateMemberMessageListIntegral.setType(1);
            updateMemberIntegral(updateMemberMessageListIntegral);

            //添加积分修改记录
            Map<String, Object> pointParam = new HashMap<>();
            pointParam.put("PointsLogType", CommonType.pointsLogType.GAIN.getCode());
            pointParam.put("ClassId", CommonType.pointType.LOGIN.getCode());
            pointParam.put("PointsLogTime", new Date());
            pointParam.put("PointsLogDesc", CommonType.pointType.LOGIN.getDesc());
            pointParam.put("PointsLogFlag", "reg");
            pointParam.put("UserId", userInfo.getUserId());
            pointParam.put("PointsLogPoints", integralRules.get("ruleLogin"));
            pointParam.put("PointsLogOperate", CommonType.pointType.LOGIN.getDesc());
            userPointsLogService.insertByMap(pointParam);
        }
    }


    @Override
    public ResponseResult addGateStore(GateStoreUpdateDTO gateAddStoreDTO) {
        Map<String,Object> result = new HashMap<>();
        if(gateAddStoreDTO.getToken() != null && gateAddStoreDTO.getToken()!=""){

            UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(gateAddStoreDTO.getToken());
            if(null == userInfo.getShopId()){
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
            //校验登录名是否符合要求
            if(!VerificationUtils.isPhonePattern(gateAddStoreDTO.getPhone())){
                result.put("start",2);
                return ResponseResult.fail(BizCodeEnume.INCORRECT_PHONE_NUMBER_FORMAT);
            }
            //校验登录名
            //校验登录名下是否：1.注册；2.有店铺；3有门店
            //根据手机号查用户表是否存在
            Map<String, String> param = new HashMap<>();
            param.put("phone", gateAddStoreDTO.getPhone());
            param.put("shopType", String.valueOf(userInfo.getShopType()));
            param.put("shopId", String.valueOf(userInfo.getShopId()));
            ResponseResult rr = queryPhoneNumCount(param);
            if(null == rr || CommonStatusEnum.SUCCESS.getCode() != rr.getCode()){
                result.put("start",2);
                return ResponseResult.fail(rr.getMessage(), result);
            }
            //根据手机号查门店表
            //判断是否为品牌店铺
            Integer gataPhoneNum = 0;
            if (userInfo.getShopType() == 3){
                //走品牌店铺
                gataPhoneNum = this.baseMapper.queryGatePhoneNumCount1(gateAddStoreDTO.getPhone(),userInfo.getShopId());
            }else{
                gataPhoneNum = this.baseMapper.queryGatePhoneNumCount(gateAddStoreDTO.getPhone());
            }

            if (gataPhoneNum > 0) {
                result.put("start",2);
                return ResponseResult.fail(BizCodeEnume.REGISTERED_STORE_WITH_PHONE_NUMBER);
            }
            ////////////////////////////////////////////////////////////////////////////////////////////////////
            //存储信息
            Map<String,Object> params = new HashMap<>();
            //查询门店用户的userid
            String userId = this.baseMapper.queryGateUserId(gateAddStoreDTO.getPhone());
            if(userId != null){
                params.put("userId",userId);
            }
            if(userInfo != null && userInfo.getShopId() != null){
                params.put("shopId",userInfo.getShopId());
            }
            if(gateAddStoreDTO.getPhone() != null){
                params.put("loginName",gateAddStoreDTO.getPhone());
            }
            if(gateAddStoreDTO.getGatestoreName() != null){
                params.put("gatestoreName",gateAddStoreDTO.getGatestoreName());
            }
            if(gateAddStoreDTO.getProvince() != null){
                params.put("province",gateAddStoreDTO.getProvince());
            }
            if(gateAddStoreDTO.getCity() != null){
                params.put("city",gateAddStoreDTO.getCity());
            }
            if(gateAddStoreDTO.getCounty() != null){
                params.put("county",gateAddStoreDTO.getCounty());
            }
            if(gateAddStoreDTO.getDetailAddress() != null){
                params.put("detailAddress",gateAddStoreDTO.getDetailAddress());
            }
            if(gateAddStoreDTO.getLongitude() != null){
                params.put("longitude",gateAddStoreDTO.getLongitude().toString());
            }
            if(gateAddStoreDTO.getLatitude() != null){
                params.put("latitude",gateAddStoreDTO.getLatitude().toString());
            }
            if(gateAddStoreDTO.getGatePhone() != null){
                params.put("gatePhone",gateAddStoreDTO.getGatePhone());
            }
            if(gateAddStoreDTO.getBusinessTime() != null){
                params.put("businessTime",gateAddStoreDTO.getBusinessTime());
            }
            if(gateAddStoreDTO.getTrafficRoute() != null){
                params.put("trafficRoute",gateAddStoreDTO.getTrafficRoute());
            }
            if(gateAddStoreDTO.getGatePic() != null){
                params.put("gatePic",gateAddStoreDTO.getGatePic());
            }
            params.put("state",1);
            params.put("limits","chain_stockList,chain_self,chain_out");
            params.put("shopType",userInfo.getShopType());
            Integer register = this.baseMapper.registerGateStore(params);
            if(register == 1){
                result.put("start",1);
                return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
            }else{
                result.put("start",2);
                return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
            }
        }else{
            result.put("start",2);
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult registerCreateqr(Map<String, String> paraMap) throws NotFoundException, IOException, WriterException {
            String token = paraMap.get("token");
            UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
            String shopId = userInfo.getShopId().toString();
            String url = YFConfig.QR_CODE_REGISTER_SHOPID + shopId;
            String baseString = QRCodeUtil.text2Base64Str(url);
            Map<String, String> returnMap = new HashMap<String, String>();
            returnMap.put("url", url);
            returnMap.put("baseString", baseString);
            return ResponseResult.success(returnMap);
    }

    @Override
    public ResponseResult queryMember(Map<String, Object> param) {
        String token = (String) param.get("token");
        HashMap<Object, Object> map = new HashMap<>();
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(null, token);
        Integer integer = null;
        String shopId = null;
        if (userPermissionsResult.getFlag()) {
            // 根据code存储用户信息
            UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
            shopId = userInfo.getShopId();
        }
        param.put("shopId",shopId);
        IPage<BrandMemberVO> page=this.baseMapper.querymember(new Query<BrandMemberVO>().getPage(param),
                param);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult memberMessageListExp(Map<String, Object> param) {
        if(null == param.get("token")){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
        }
        String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + param.get("token"));// 获取user信息
        if (userinfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        String[] title = {"会员名称", "会员ID", "手机号码", "注册时间", "性别", "最后登陆时间", "购买次数", "支付总额"};
        List<Map<String, String>> list = Lists.newArrayList();
        List<MemberMessageListVO> result = querymember1(param);
        if(result.size()>=30000){
            return ResponseResult.fail(0, "请小于三万条");
        }
        for (MemberMessageListVO res : result) {
            if(res.getUserGender() !=null){
                switch (res.getUserGender()) {
                    case "0":
                        res.setUserGender("保密");
                        break;
                    case "1":
                        res.setUserGender("男");
                        break;
                    case "2":
                        res.setUserGender("女");
                        break;
                    default:
                        res.setUserGender("");
                        break;
                }
            }else{
                res.setUserGender("");
            }
            if (null != res.getUserRegTime()) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            }else{
                res.setUserRegTime("");
            }

            if(null == res.getSumAmount()){
                res.setSumAmount(new BigDecimal("0.00"));
            }

            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            map.put("会员名称", res.getUserName());
            map.put("会员ID", res.getUserId() + "");
            map.put("手机号码", res.getUserMobile() + "");
            map.put("注册时间", res.getUserRegTime() + "");
            map.put("最后登陆时间", res.getUserLastloginTime() + "");
            map.put("支付总额", res.getSumAmount() + "");

            list.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(title, map,
                new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult updatememberstatus(Map<String, Object> param) {
        Integer returnFlag = 0;
        if (RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + param.get("token"))) {
            Integer integer = this.baseMapper.update(null,new LambdaUpdateWrapper<UserInfoEntity>()
                             .eq(UserInfoEntity::getUserId,param.get("userId").toString())
                             .set(UserInfoEntity::getIsDelete,param.get("isDelete").toString()));
            if (integer > 0 ){
                return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
            }else{
                return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }

    @Override
    public ResponseResult checkphone(String userMobile) {
        Map map = this.baseMapper.checkphone(userMobile);
        if (!CollectionUtils.isEmpty(map)){
            Integer userState = (Integer) map.get("user_state");
            String userId = String.valueOf(map.get("user_id"));
            if (userState == 1 || userState == 2){
                return ResponseResult.success(1,"账号正常",1);
            }else {
                //查看审核状态
                Integer integer = this.baseMapper.checkbusinessphone(userId);
                if (integer != null && integer == 0) {
                    return ResponseResult.success(1,"账号审核中",2);
                } else if (integer != null && integer == 1) {
                    return ResponseResult.success(1,"账号正常",1);
                } else if (integer != null && integer == 2) {
                    return ResponseResult.success(1,"账号审核失败",3);
                }
            }
        }
        return ResponseResult.success(1,"无账号信息",0);
    }

    @Override
    public ResponseResult updateUserBirthAndGender(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
        if(null == userInfo.getUserId()){
            return ResponseResult.fail(2, "用户信息为空!");
        }
        UpdateWrapper<UserInfoDetaileEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("user_id",userInfo.getUserId());
        if(StringUtils.isNotBlank(paraMap.get("userBirth"))){
            updateWrapper.set("user_birth",paraMap.get("userBirth"));
        }
        if(StringUtils.isNotBlank(paraMap.get("userGender"))){
            updateWrapper.set("user_gender",paraMap.get("userGender"));
        }
        userInfoDetailMapper.update(null,updateWrapper);
        return ResponseResult.success(1,"修改用户信息成功");
    }

    @Override
    public ResponseResult updateVerifiedInfo(Map<String, Object> paraMap) {
        String token = String.valueOf(paraMap.get("token"));
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
        paraMap.put("userId", userId);
        paraMap.put("userIdentityFaceLogo", paraMap.get("faceLogo"));
        paraMap.put("userIdentityFontLogo", paraMap.get("fontLogo"));
        if(paraMap.get("validateLongTerm") == null){
            paraMap.put("validateLongTerm", paraMap.get("userIdentityEndTime") != null && paraMap.get("userIdentityEndTime").equals("") ? 0 : 1);
        }else {
            paraMap.put("validateLongTerm", paraMap.get("validateLongTerm"));
        }
        Integer integer = userInfoDetailMapper.updateUcenterInfo(paraMap);
        if (1 == integer) {
            //修改用户状态为已认证
            this.baseMapper.updateUserStart(userId);
            UserInfoVO userInfo = this.baseMapper.getUserInfoByUserId(userId);
            String user = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
            UserInfoDTO userInfoDTO = JSON.parseObject(user,UserInfoDTO.class);
            if (userInfoDTO == null) {
                userInfoDTO = new UserInfoDTO();
            }
            userInfoDTO.setUser(userInfo);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(userInfoDTO), YFConfig.TOKEN_OUTTIME);
            return ResponseResult.success(1,"认证成功");
        }
        return ResponseResult.fail(0,"认证失败");
    }

    @Override
    public ResponseResult checkPhoneByPlatform(Map<String, Object> map) {
        //根据手机号查询用户id
        String phone =this.baseMapper.selectOne(new LambdaQueryWrapper<UserInfoEntity>()
                        .eq(UserInfoEntity::getUserMobile,String.valueOf(map.get("phone")))
                        .isNull(UserInfoEntity::getShopId)).getUserId();
        if (phone != null){
            return ResponseResult.success("已注册");
        }
        return ResponseResult.fail(0, "未注册");
    }

    @Override
    public AcquiescenceVO queryUserInfoByjob(String userId) {
        AcquiescenceVO vo = this.baseMapper.queryUserInfoByjob(userId);
        return vo;
    }

    public List<MemberMessageListVO> querymember1(Map<String, Object> param) {
        String token = (String) param.get("token");
        HashMap<Object, Object> map = new HashMap<>();
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(null, token);
        Integer integer = null;
        String shopId = null;
        if (userPermissionsResult.getFlag()) {
            // 根据code存储用户信息
            String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
            UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
            shopId = userInfo.getShopId();
        }
        param.put("shopId",shopId);
        IPage<MemberMessageListVO> page=this.baseMapper.querymember1(new Query<MemberMessageListVO>().getPage(param),
                param);

        return  page.getRecords();
    }

    @Override
    public ResponseResult updateLoginTimeCount(String userId) {
        Integer num = this.baseMapper.updateLoginTimeCount(userId);
        return ResponseResult.success();
    }


    public ResponseResult checkPassword(String password) {
        Map<String, String> returnMap = new HashMap<String, String>();
        String configLength = baseServiceClient.selectConfigValueFeign(CommonType.configKey.PASSWORD_LENGTH.getDesc());
        if (password.length() < Integer.parseInt(configLength)) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"密码长度不满足要求！必须为" + configLength + "位以上");
        }

        //1-纯数字;2-纯英文;3-数字英文;4-数字英文符号
        String configFormat = baseServiceClient.selectConfigValueFeign(CommonType.configKey.PASSWORD_FORMAT.getDesc());
        Pattern pattern = null;
        String desc = "";
        if ("1".equals(configFormat)) {
            pattern = Pattern.compile("^[0-9]*$");
            desc = "密码只能为纯数字！";
        } else if ("2".equals(configFormat)) {
            pattern = Pattern.compile("^[A-Za-z]+$");
            desc = "密码只能为纯英文！";
        } else if ("3".equals(configFormat)) {
            pattern = Pattern.compile("^[A-Za-z0-9]+$");
            desc = "密码只能为数字和英文的组合！";
        } else if ("4".equals(configFormat)) {
            pattern = Pattern.compile("^[0-9A-Za-z^%&@',;=?$]*$");
            desc = "密码只能为数字、英文和符号的组合！";
        }


        Matcher match = pattern.matcher(password);
        if (!match.matches()) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),desc);
        }
        return ResponseResult.success(BizCodeEnume.VERIFICATION_SUCCESSFUL);
    }
}
